from typing import Dict
import os

CPU_SCRIPT_RULES = [
    {
        "script": "cpu_负载过高.sh",
        "keywords": ["负载", "load", "cpu", "利用率"],
        "weight": 3
    },
    {
        "script": "cpu_高中断.sh",
        "keywords": ["中断", "interrupt", "irq"],
        "weight": 2
    },
    {
        "script": "cpu_进程调度延迟.sh",
        "keywords": ["调度", "scheduler", "延迟", "latency"],
        "weight": 1
    }
]
# 用于根据异常特征选择最合适的脚本。
def select_script_for_anomaly(anomaly: Dict) -> str:
    # 从异常信息中提取关键字段：
    # root_cause: 根本原因，转换为小写
    # evidence: 证据列表，连接成字符串并转换为小写
    # severity: 严重性等级，默认值为0
    root_cause = anomaly.get("root_cause", "").lower()
    evidence = " ".join(anomaly.get("evidence", [])).lower()
    severity = anomaly.get("severity", 0)
    # 初始化最佳评分和最佳脚本：
    # best_score 设置为-1，确保任何非负评分都会被选中
    # best_script 默认选择第一个规则的脚本
    best_score = -1
    best_script = CPU_SCRIPT_RULES[0]["script"]
    # 遍历当前规则的所有关键词
    # 如果关键词出现在根本原因或证据中，将该规则的权重加到评分中
    for rule in CPU_SCRIPT_RULES:
        score = 0
        for kw in rule["keywords"]:
            if kw in root_cause or kw in evidence:
                score += rule["weight"]
        # 严重性加权
        # 根据严重性等级进行加权：
        # 严重性≥8：加2分
        # 严重性≥6：加1分
        # 其他情况：不加分
        if severity >= 8:
            score += 2
        elif severity >= 6:
            score += 1
        # 证据数量加权
        # 根据证据数量进行加权，每条证据加0.5分
        score += len(anomaly.get("evidence", [])) * 0.5
        if score > best_score:
            best_score = score
            best_script = rule["script"]
    return best_script 